from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from sirogi.letter.models import Letter
from sirogi.users.models import SirogiUser
from django.contrib.auth.decorators import user_passes_test
from django.template import RequestContext

@user_passes_test(lambda u: u.has_perm('letter.add_letter'), login_url='/login/')
def index(request):
    #creo la lista de los usuarios
    #if (request.user.role == 'G'):
	#return render_to_response('letter/permission.html')
    all_results = list(SirogiUser.objects.all())
    all_results.remove(request.user) 
    
    #elimino todos los usuarios invitados. #CORRECCION POR TEST
    for i in all_results:
        if i.role == 'G':
            all_results.remove(i) 
  
    return render_to_response('letter/write_letter.html', {'results_user': all_results}, RequestContext(request))
    
#==================================================

@user_passes_test(lambda u: u.has_perm('letter.add_letter'), login_url='/login/')
def save(request):
    try:
        letter = Letter()
        recipient = get_object_or_404(SirogiUser, NIC=request.POST['recipient'])
        user = request.user
        
        letter.Sender =  user.username #request.POST['sender']
        letter.Recipient = recipient #.username
        letter.Subject =  request.POST['subject']
        letter.Body =  request.POST['body']
        letter.Read = False
    
        letter.save()
        #retorno que no ocurrio ningun error
        
        return render_to_response('letter/write_letter.html', {'ret':True},RequestContext(request))
    except:
        return render_to_response('letter/permission.html',RequestContext(request))


#==================================================
@user_passes_test(lambda u: u.has_perm('letter.add_letter'), login_url='/login/')
def listl(request):
    #tomo el id del usuario actual y busco las cartas que este tiene asociadas. 
    user = request.user
    #retorno una lista de las cartas que no fueorn leidas
    
    letters = Letter.objects.filter(Recipient = user)
    return render_to_response('letter/list_letter.html', {'letters':letters},RequestContext(request))


#==================================================
@user_passes_test(lambda u: u.has_perm('letter.add_letter'), login_url='/login/')
def read(request, id_letter):
    #Leo la carta. 
    try:
        letter = get_object_or_404(Letter, id = id_letter)
        
        if check_user(request, letter.Recipient):
           letter.Read = True
           letter.save()
           #Retorno la carta
           return render_to_response('letter/read_letter.html', {'letter':letter},RequestContext(request))
        else:
            return render_to_response('letter/read_letter.html', {'message':'You dont have permission for this action.'},RequestContext(request))
    except Http404:
        #Si no existe no retorno ninguna carta
        return render_to_response('letter/permission.html',RequestContext(request))


#==================================================
@user_passes_test(lambda u: u.has_perm('letter.delete_letter'))
def delete(request, id_letter):
    try:
        if (request.user.role == 'G'):
            return render_to_response('letter/permission.html',RequestContext(request))

            #verico que el usuario este eliminado un documento propio y no de otro
        letter = get_object_or_404(Letter, id = id_letter)

        if check_user(request, letter.Recipient):
            letter.delete()
            return HttpResponseRedirect('/letter/list/')#, {'message':'The letter was delete'})
        else:
            return render_to_response('letter/list_letter.html', {'message':'You dont have permission for this action.'},RequestContext(request))
    except Http404:	
        #Si no existe no retorno ninguna carta
            return render_to_response('letter/permission.html',RequestContext(request))
    except:
            return render_to_response('letter/list_letter.html', {'message':'Error. Contact the administrator.'},RequestContext(request))

#==================================================

def check_user(request, user):
    #Verifica que el usuario pasado como parametro sea el mismo que el usuario actual
    return user == request.user